package pers.karl.security.controller;

import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author karl
 * @description:
 * @create 2020-08-13 23:01
 */
@RestController
public class HomeController {

    private static final String DEFAULT_CSRF_TOKEN_ATTR_NAME = HttpSessionCsrfTokenRepository.class
            .getName().concat(".CSRF_TOKEN");

    @GetMapping("/csrf")
    public Map<String,Object> csrf(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            CsrfToken token = (CsrfToken) session.getAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME);
            if (token != null) {

                Map<String,Object> resultInfo = new HashMap<>(2);
                resultInfo.put("code", 200);
                resultInfo.put("data", token.getToken());
                return resultInfo;
            }
        }

        Map<String,Object> resultInfo = new HashMap<>(2);
        resultInfo.put("code", 500);
        resultInfo.put("msg", "token generated fail");
        return resultInfo;
    }

}
